from django.contrib import admin
from .models import MyUser
from .models import Subject
from django.utils.html import format_html
import markdown
# Register your models here.




class UserInline(admin.StackedInline):
    model = MyUser
    can_delete = False
    verbose_name_plural = "用户"


# Define a new User admin

class SubjectAdmin(admin.ModelAdmin):
    list_display = [
        "id",
        "name",
    ]
    search_fields = ("name",)

class UserAdmin(admin.ModelAdmin):
    # inlines = (UserInline,)
    list_display = [
        "id",
        "user",
        "real_name",        
        "age",
        "gender",
        "user_type",
        "is_active",
        "score",
        "teacher",
        "workload",  
        "note_pre",
    ]
    # 设置哪些字段可以点击进入编辑界面
    list_display_links = (
        "id",
        "user",
        "real_name",
    )
    list_filter = (
        "user",
        "user_type",
        "real_name",
    )
    search_fields = ("real_name","user__username",)
    """设置可编辑字段"""
    list_editable = (
        "workload",
    )

    """按id排序"""
    ordering = ("user_type","id")
    # 使用搜索来代替选择
    autocomplete_fields = ("user","teacher","subjects")

    list_per_page = 20

    def id(self, obj):
        return obj.user.id

    def 上次登录(self, obj):
        return obj.user.last_login
    
    @admin.display(description="是否有效")
    def is_active(self,obj):
        return obj.user.is_active
    
    @admin.display(description="备注")
    def note_pre(self, obj):
        text = markdown.markdown(obj.note, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
            'markdown.extensions.toc',
        ])
        return format_html(text if len(text) < 20 else text[:20] + '......')
    

# admin.site.unregister(User)  # 注销原有用户管理面板
# admin.site.register(User, UserAdmin)  # 重新注册用户管理面板

admin.site.register(MyUser, UserAdmin)
admin.site.register(Subject, SubjectAdmin)

admin.site.site_title = "后台管理"
admin.site.site_header = "天月山水后台管理"
admin.site.index_title = '天月山水后台管理'